package org.aplombh.java.leetcode.dailyTopic;

public class _795区间子数组个数 {
    public static void main(String[] args) {
        System.out.println(new Solution795_1().numSubarrayBoundedMax(new int[]{876, 880, 482, 260, 132, 421, 732, 703, 795, 420, 871, 445, 400, 291, 358, 589, 617, 202, 755, 810, 227, 813, 549, 791, 418, 528, 835, 401, 526, 584, 873, 662, 13, 314, 988, 101, 299, 816, 833, 224, 160, 852, 179, 769, 646, 558, 661, 808, 651, 982, 878, 918, 406, 551, 467, 87, 139, 387, 16, 531, 307, 389, 939, 551, 613, 36, 528, 460, 404, 314, 66, 111, 458, 531, 944, 461, 951, 419, 82, 896, 467, 353, 704, 905, 705, 760, 61, 422, 395, 298, 127, 516, 153, 299, 801, 341, 668, 598, 98, 241}, 658, 719));
        System.out.println(new Solution795_2().numSubarrayBoundedMax(new int[]{876, 880, 482, 260, 132, 421, 732, 703, 795, 420, 871, 445, 400, 291, 358, 589, 617, 202, 755, 810, 227, 813, 549, 791, 418, 528, 835, 401, 526, 584, 873, 662, 13, 314, 988, 101, 299, 816, 833, 224, 160, 852, 179, 769, 646, 558, 661, 808, 651, 982, 878, 918, 406, 551, 467, 87, 139, 387, 16, 531, 307, 389, 939, 551, 613, 36, 528, 460, 404, 314, 66, 111, 458, 531, 944, 461, 951, 419, 82, 896, 467, 353, 704, 905, 705, 760, 61, 422, 395, 298, 127, 516, 153, 299, 801, 341, 668, 598, 98, 241}, 658, 719));
    }
}

class Solution795_1 {

    int left, right;

    public int numSubarrayBoundedMax(int[] nums, int left, int right) {
        int ans = 0;
        int cou = 0;
        int len = 0;
        boolean flag = false;

        for (int num : nums) {
            if (num <= right) {
                len++;
                flag = true;
                if (left <= num) {
                    cou = len;
                }

            } else {
                flag = false;
                len = 0;
                cou = 0;
            }
            if (flag)
                ans += cou;

        }
        return ans;
    }
}

class Solution795_2 {
    public int numSubarrayBoundedMax(int[] nums, int left, int right) {
        return count(nums, right) - count(nums, left - 1);
    }

    public int count(int[] nums, int lower) {
        int res = 0, cur = 0;
        for (int x : nums) {
            cur = (x <= lower ? cur + 1 : 0);
            res += cur;
        }
        return res;
    }
}